package com.ball.common.interceptors;

import com.ball.common.utils.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Configuration
public class TokenInterceptor implements HandlerInterceptor {





    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String authorization = request.getHeader("Authorization");

        if (authorization == null ) {
            // 缺少或格式不正确的 Authorization 头
            sendError(response, HttpStatus.UNAUTHORIZED, "Missing or invalid Authorization header");
            return false;
        }

        String token = authorization.substring("Bearer ".length());
        try {
            // 解码 JWT，提取 Claims 对象


            // 验证 token 是否需要更新
            int tokenUpdateStatus = AppJwtUtil.verifyToken(AppJwtUtil.getClaimsBody(token));

            if (tokenUpdateStatus == 1 || tokenUpdateStatus == 2) {
                // 需要更新 token，返回错误码 555
                sendError(response, HttpStatus.FORBIDDEN, "Token update required", 555);
                return false;
            }

            // token 验证通过，继续处理请求
            return true;
        } catch (Exception e) {
            sendError(response, HttpStatus.UNAUTHORIZED, "Invalid token");
            return false;
        }
    }

    private void sendError(HttpServletResponse response, HttpStatus status, String message) {
        sendError(response, status, message, null);
    }

    private void sendError(HttpServletResponse response, HttpStatus status, String message, Integer customErrorCode) {
        response.setStatus(status.value());
        response.setContentType("application/json");
        try {
            if (customErrorCode != null) {
                response.getWriter().write("{\"message\":\"" + message + "\", \"code\":" + customErrorCode + "}");
            } else {
                response.getWriter().write("{\"message\":\"" + message + "\"}");
            }
        } catch (Exception e) {
            // Handle any I/O errors here
        }
    }


}